package com.neulogistics.contrib.warehouse.infrastructure.persistence.converter;

import cn.hutool.json.JSONUtil;
import com.neulogistics.contrib.warehouse.domain.model.aggregate.Warehouse;
import com.neulogistics.contrib.warehouse.domain.model.enumeration.WarehouseLevel;
import com.neulogistics.contrib.warehouse.domain.model.valueobject.Address;
import com.neulogistics.contrib.warehouse.infrastructure.persistence.orm.po.WarehousePO;
import org.springframework.beans.BeanUtils;

public class WarehouseEntityPOConverter {
    public static WarehousePO entityToPO(Warehouse warehouse){
        if(warehouse == null)
            return null;

        WarehousePO warehousePO = new WarehousePO();
        // 复制普通属性
        BeanUtils.copyProperties(warehouse, warehousePO);
        // 地址值对象转换为json对象
        if(warehouse.getWarehouseAddress() != null){
            warehousePO.setWarehouseAddress(JSONUtil.parseObj(warehouse.getWarehouseAddress()));
        }
        // 库房等级转化为Integer
        if(warehouse.getWarehouseLevel() != null){
            warehousePO.setWarehouseLevel(warehouse.getWarehouseLevel().id);
        }

        return warehousePO;
    }

    public static Warehouse POToEntity(WarehousePO warehousePO){
        if(warehousePO == null)
            return null;

        Warehouse warehouse = new Warehouse();
        // 复制普通属性, id是可以在这里被复制进去的
        BeanUtils.copyProperties(warehousePO, warehouse);
        // json对象转换为值对象
        warehouse.setWarehouseAddress(JSONUtil.toBean(warehousePO.getWarehouseAddress(), Address.class));
        // 枚举类型转换
        warehouse.setWarehouseLevel(WarehouseLevel.fromValue(warehousePO.getWarehouseLevel(), WarehouseLevel.class));
        return warehouse;
    }

}
